import { useCallback } from 'react';
import { REG_PROTOCOL } from 'esy-ui';
import { useNavigate as useAutoNavigate, NavigateOptions } from 'react-router-dom';
import { useUserInfoStore } from '@/mobx';
import { noSignAceRouter } from '@/constants';

export const useNavigation = () => {
  const autoNavigate = useAutoNavigate();
  const { userInfo } = useUserInfoStore();
  const navigate = useCallback(
    (p, option?: NavigateOptions) => {
      if (REG_PROTOCOL.test(p)) {
        const w = window.open('about:_blank');
        if (w) w.location.href = p;
        return;
      }
      if (!userInfo?.token) {
        // 未登录
        if (typeof p === 'string' && !noSignAceRouter.test(p)) {
          autoNavigate('/login', { replace: true });
        } else if (!noSignAceRouter.test(p)) {
          autoNavigate('/login', { replace: true });
        } else {
          autoNavigate(p, option);
        }
        return;
      }
      autoNavigate(p, option);
    },
    [autoNavigate, userInfo?.token],
  );

  return navigate;
};
